webview_find_doxygen(${WEBVIEW_IS_CI})

if(NOT Doxygen_FOUND)
    message(WARNING "Skipping docs as Doxygen was not found")
    return()
endif()

# We can set this to "-$<CONFIG>" if we need per-config documentation
set(CONFIG_SUFFIX "")
set(DOXYFILE_HAVE_DOT YES)
set(DOXYFILE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/output${CONFIG_SUFFIX}")
set(DOXYFILE_CLANG_DATABASE_PATH "${PROJECT_BINARY_DIR}")

get_target_property(CORE_SOURCE_DIR webview::core SOURCE_DIR)
set(DOXYFILE_INPUT "${CORE_SOURCE_DIR}/include")

set(RUN_DOXYGEN_FILE "${CMAKE_CURRENT_BINARY_DIR}/run_doxygen${CONFIG_SUFFIX}.cmake")

file(GLOB_RECURSE DOCS_INPUT_FILES CONFIGURE_DEPENDS "${DOXYFILE_INPUT}/**")

file(GENERATE
    OUTPUT "${RUN_DOXYGEN_FILE}"
    CONTENT "set(DOXYGEN_EXECUTABLE \"${DOXYGEN_EXECUTABLE}\")\n\
set(PROJECT_NAME \"${PROJECT_NAME}\")\n\
set(PROJECT_VERSION \"${PROJECT_VERSION}\")\n\
set(PROJECT_DESCRIPTION \"${PROJECT_DESCRIPTION}\")\n\
set(DOXYFILE_HAVE_DOT \"${DOXYFILE_HAVE_DOT}\")\n\
set(DOXYFILE_OUTPUT_DIRECTORY \"${DOXYFILE_OUTPUT_DIRECTORY}\")\n\
set(DOXYFILE_INPUT \"${DOXYFILE_INPUT}\")\n\
set(DOXYFILE_CLANG_DATABASE_PATH \"${DOXYFILE_CLANG_DATABASE_PATH}\")\n\
configure_file(\"${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in\" \"${CMAKE_CURRENT_BINARY_DIR}/Doxyfile${CONFIG_SUFFIX}\" @ONLY)\n\
execute_process(COMMAND \"${DOXYGEN_EXECUTABLE}\" \"${CMAKE_CURRENT_BINARY_DIR}/Doxyfile${CONFIG_SUFFIX}\")"
)

set(API_DOCS_STAMP_FILE "${CMAKE_CURRENT_BINARY_DIR}/webview_api_docs${CONFIG_SUFFIX}.stamp")
add_custom_command(
    OUTPUT "${API_DOCS_STAMP_FILE}"
    COMMAND "${CMAKE_COMMAND}" -E touch "${API_DOCS_STAMP_FILE}"
    COMMAND "${CMAKE_COMMAND}" -E rm -rf "${DOXYFILE_OUTPUT_DIRECTORY}"
    COMMAND "${CMAKE_COMMAND}" -P "${RUN_DOXYGEN_FILE}"
    DEPENDS ${DOCS_INPUT_FILES} "${RUN_DOXYGEN_FILE}"
    VERBATIM)

add_custom_target(webview_api_docs ALL DEPENDS "${API_DOCS_STAMP_FILE}")

if(WEBVIEW_INSTALL_DOCS)
    install(DIRECTORY "${DOXYFILE_OUTPUT_DIRECTORY}/html"
        DESTINATION "${CMAKE_INSTALL_DOCDIR}"
        COMPONENT webview_api_docs)
endif()
